<?php

namespace app\admin\controller;

use app\common\model\Member;
use app\common\model\MemberFinance;
use app\common\model\MemberPackages;
use app\common\model\TradersOrder;
use app\common\model\Withdrawal;
use think\Db;
use think\Request;
use app\common\api\controller\Bonus;
use app\common\controller\Wechat;

class TradingHall extends Home
{
    /**
     * 公司充值或扣币
     */
    public function handleMoney()
    {
        $type = input('type');
        if (request()->isPost()) {

            $code = input('code');
            if ($code != session('email_code')) {
                $this->error('邮箱验证码错误');
            }

            $money = input('money');
            $moneytype = input('moneytype', 1);
            if ($money <= 0) {
                $this->error('金额不能小于0');
            }
            $usernumber = input('usernumber');
            $user = Db('member')->where('usernumber', $usernumber)->where('status', '>=', 1)->find();
            if (!$user) {
                $this->error('用户不存在或未激活');
            }

            $financeObj = MemberFinance::where('uid', $user['uid'])->find();

            switch ($moneytype) {
                case 1:
                    $field1 = 'hasbill';
                    $field2 = 'allbill';
                    break;
                case 2:
                    $field1 = 'hasmoney';
                    $field2 = 'allmoney';
                    break;
                case 3:
                    $field1 = 'hascp';
                    $field2 = 'allcp';
                    break;
            }

            if ($type == 'inc') {
                $recordtype = 1;
                $changetype = 21;
                $user_data[$field1] = $financeObj->$field1 + $money;
                $user_data[$field2] = $financeObj->$field2 + $money;
            } else {
                $recordtype = 0;
                $changetype = 29;
                if ($financeObj->$field1 < $money) {
                    $this->error('账户余额不足！');
                }
                $user_data[$field1] = $financeObj->$field1 - $money;
            }

            $res = Db('member_finance')->where('uid', $user['uid'])->update($user_data);
            if ($res) {
                $arr = array('recordtype' => $recordtype, 'changetype' => $changetype, 'moneytype' => $moneytype);
                $money_arr = array('money' => $money, 'hasmoney' => $user_data[$field1]);
                money_change($arr, $user['uid'], 0, $money_arr);

                session('email_code', null);

//                $title='充值成功';
//                $content = '公司已经给你充值'.$money.$fieldname;
//                $res = CommonApi::sendMessage($touser['uid'],$title,$content);
                $this->success('操作成功', url('bonusChange?changetype=' . $changetype));
            } else {
                $this->error('操作失败');
            }
        } else {
            $uid = input('id');
            $userinfo = Db('member')->where('uid', $uid)->where('status', 1)->find();

            if (!self::$adminInfo['email']) {
                $this->error('缺少邮箱，不可充值扣币');
            }

            $this->assign('email', self::$adminInfo['email']);

            $this->assign('userinfo', $userinfo);
            $this->assign('type', $type);
            $this->assign('title', '充币扣币');
            return $this->fetch('handlemoney');
        }
    }

    /**
     * 充值记录
     */
    public function moneyIncRecord()
    {
        $where = $this->getMap('createtime');
        $map = $where['map'];
        $maps = $where['maps'];
        $usernumber = input('usernumber');


        if (!empty($usernumber)) {
            $numwhere['usernumber'] = $usernumber;
            $user = Db('member')->where($numwhere)->find();
            if (!$user) {
                $this->error('用户不存在！');
            } else {
                $map['targetuserid'] = $user['uid'];
            }
        }

        $map['status'] = array('neq', 0);
        $list = Db('recharge')->where($map)->paginate(20);
        $page = $list->render();
        $list = $list->toArray();
        $this->assign('_list', $list['data']);
        $this->assign('page', $page);

        $arr = [
            [
                'type' => 'input',
                'name' => 'usernumber',
                'inputid' => '',
                'readonly' => '',
                'title' => '会员账号',
                'value' => $usernumber,
            ]
        ];
        $this->searchCondition($maps, $arr);

        $this->assign('title', '充值记录');
        return $this->fetch();
    }

    /**
     * 提现
     */
    public function wdRecord()
    {
        $where = $this->getMap('createtime');
        $map = $where['map'];
        $maps = $where['maps'];
        $usernumber = input('usernumber');
        $status = input('status', -2);

        if (!empty($usernumber)) {
            $maps['usernumber'] = $usernumber;
            $user = Db('member')->where('usernumber', $usernumber)->find();
            if (!$user) {
                $this->error('用户不存在！');
            } else {
                $map['userid'] = $user['uid'];
            }
        }
        if ($status > -2) {
            $maps['status'] = $map['status'] = $status;
        }
        $list = Db('withdrawal')->where($map)->order('id desc')->paginate(20, false, ['query' => $maps]);
        $page = $list->render();
        $this->assign('_list', $list);
        $this->assign('page', $page);

        $arr = [
            [
                'type' => 'input',
                'name' => 'usernumber',
                'inputid' => '',
                'readonly' => '',
                'title' => '会员账号',
                'value' => $usernumber,
            ],
            [
                'type' => 'select',
                'name' => 'status',
                'inputid' => '',
                'readonly' => '',
                'title' => '状态',
                'option' => [
                    -2 => '全部',
                    -1 => '拒批',
                    0 => '尚未审核',
                    1 => '同意'
                ],
                'value' => $status,
            ]
        ];
        $this->searchCondition($maps, $arr);

        /*提现统计*/
        $money = Db('withdrawal')->sum('money');
        $fee = Db('withdrawal')->sum('fee');
        $total = $money + $fee;
        /*未审核*/
        $money1 = Db('withdrawal')->where('status', 0)->sum('money');
        $fee1 = Db('withdrawal')->where('status', 0)->sum('fee');
        $total1 = $money1 + $fee1;
        /*拒批*/
        $money2 = Db('withdrawal')->where('status', -1)->sum('money');
        $fee2 = Db('withdrawal')->where('status', -1)->sum('fee');
        $total2 = $money2 + $fee2;
        /*同意*/
        $money3 = Db('withdrawal')->where('status', 1)->sum('money');
        $fee3 = Db('withdrawal')->where('status', 1)->sum('fee');
        $total3 = $money3 + $fee3;

        $this->assign('total', $total);
        $this->assign('total1', $total1);
        $this->assign('total2', $total2);
        $this->assign('total3', $total3);

        $this->assign('search', url('wdRecordd'));
        $this->assign('title', '提现');
        return $this->fetch('wdrecord');
    }

    public function wdRecordd()
    {
        $where = $this->getMap('createtime');
        $map = $where['map'];
        $maps = $where['maps'];
        $status = input('status', -2);

        if ($status > -2) {
            $maps['status'] = $map['status'] = $status;
        }
        $list = Db('withdrawal')->where($map)->select();
        $title = "提现";
        $a = array(
            array('date', '申请时间'),
            array('usernumber', '会员编号'),
            array('realname', '会员姓名'),
            array('total', '提现金额'),
            array('money', '实得金额'),
            array('fee', '手续费'),
            array('alipay', '支付宝号'),
            array('bankname', '开户银行'),
            array('banknumber', '银行卡号'),
            array('status', '申请状态'),
            array('handtime', '处理时间')
        );
        foreach ($list as $k => &$v) {
            $v['date'] = date('Y-m-d H:i:s', $v['createtime']);
            $v['usernumber'] = getInfo('usernumber', $v['userid']);
            $v['realname'] = getInfo('realname', $v['userid']);
            $v['total'] = $v['money'] + $v['fee'];

            switch ($v['status']) {
                case -1:
                    $v['status'] = '申请拒批';
                    $v['handtime'] = date('Y-m-d H:i:s', $v['handtime']);
                    break;
                case 0:
                    $v['status'] = '正在审核';
                    $v['handtime'] = '正在审核';
                    break;
                case 1:
                    $v['status'] = '申请获批';
                    $v['handtime'] = date('Y-m-d H:i:s', $v['handtime']);
                    break;
            }
        }

        exportExcel($title, $a, $list);
    }

    /**
     * 提现同意
     */
    public function agree()
    {
//        $id = input('id');
//        $wdinfo = Db('withdrawal')->where(array('id' => $id))->find();
//        $user = Db('member')->where('uid', $wdinfo['userid'])->find();
//
//        $wechat = new Wechat();
//        $result = $wechat->payment($user['open_id'], $wdinfo['money']);

        $res = $this->wdAction(1);
        if ($res) {
            $this->success('操作成功', url('wdRecord?status=1'));
        } else {
            $this->success('操作失败');
        }
        $this->success('提现成功！');
    }

    private function wdAction($status)
    {
        $type = input('type');
        switch ($type) {
            case 1:
                $wdinfos = Db('withdrawal')->where('status', 0)->select();
                if ($wdinfos) {
                    foreach ($wdinfos as $v) {
                        self::wdAction1($status, $v['id']);
                    }
                }
                break;
            case 2:
                $id = input('id');
                self::wdAction1($status, $id);
                break;
        }
        return true;
    }

    private function wdAction1($status, $id)
    {
        $wdinfo = Db('withdrawal')->where(array('id' => $id))->find();
        if ($wdinfo['status'] != 0) {
            $this->error('该申请已审批');
        }
        $user = Db('member')->where(array('uid' => $wdinfo['userid']))->find();
        if (empty($user)) {
            $this->error('该申请人已不存在');
        }

        $data['status'] = $status;
        $data['handtime'] = time();
        Db('withdrawal')->where(array('id' => $id))->update($data);
    }

    /**
     * 提现拒批
     */
    public function refuse()
    {
        $status = -1;
        $type = input('type');
        switch ($type) {
            case 1:
                $wdinfos = Db('withdrawal')->where('status', 0)->select();
                if ($wdinfos) {
                    foreach ($wdinfos as $v) {
                        self::wdAction1($status, $v['id']);
                        $wdMoney = $v['money'] + $v['fee'];
                        $financeObj = MemberFinance::where('uid', $v['userid'])->find();
                        $financeObj->hasmoney += $wdMoney;
                        $res = $financeObj->save();
                        if ($res) {
                            $type = array('recordtype' => 1, 'changetype' => 31, 'moneytype' => 2);
                            $money = array('money' => $wdMoney, 'hasmoney' => $financeObj->hasmoney);
                            money_change($type, $v['userid'], get_com(), $money);
                        } else {
                            $this->error('操作失败！');
                        }
                    }
                }
                $this->success('操作成功！', url('wdRecord?status=-1'));
                break;
            case 2:
                $id = input('id');
                self::wdAction1($status, $id);
                $wdinfo = Db('withdrawal')->find($id);
                $wdMoney = $wdinfo['money'] + $wdinfo['fee'];
                $financeObj = MemberFinance::where('uid', $wdinfo['userid'])->find();
                $financeObj->hasmoney += $wdMoney;
                $res = $financeObj->save();
                if ($res) {
                    $type = array('recordtype' => 1, 'changetype' => 31, 'moneytype' => 2);
                    $money = array('money' => $wdMoney, 'hasmoney' => $financeObj->hasmoney);
                    money_change($type, $wdinfo['userid'], get_com(), $money);
                    $this->success('操作成功！', url('wdRecord?status=-1'));
                } else {
                    $this->error('操作失败！');
                }
                break;
        }
    }

    /**
     * 提现详情
     * @param $id
     * @return mixed
     */
    public function withdrawal($id)
    {
        $wdinfo = Db('withdrawal')->where(array('id' => $id))->find();
        $this->assign('wdinfo', $wdinfo);
        $this->assign('id', $id);
        $this->assign('title', '提现详情');
        return $this->fetch();
    }

    /**
     * 充值申请-同意
     */
    public function rAgree()
    {
        $status = 1;
        $res = $this->reAction($status);
        if (!$res) {
            $this->error('更新失败！');
        }
        $id = input('id');
        $reinfo = Db('recharge')->find($id);
        $financeObj = MemberFinance::where(array('uid' => $reinfo['userid']))->find();
        switch ($reinfo['moneytype']) {
            case 1:
                $financeObj->hasbill += $reinfo['money'];
                $financeObj->allbill += $reinfo['money'];
                $total = $financeObj->hasbill;
                break;
            case 2:
                $financeObj->hasmoney += $reinfo['money'];
                $financeObj->allmoney += $reinfo['money'];
                $total = $financeObj->hasmoney;
                break;
            case 3:
                $financeObj->hascp += $reinfo['money'];
                $financeObj->allcp += $reinfo['money'];
                $total = $financeObj->hascp;
                break;
            default:
                $this->error('暂无该币种！');
                break;
        }

        $res = $financeObj->save();
        if ($res) {
            $type = array('recordtype' => 1, 'changetype' => 23, 'moneytype' => $reinfo['moneytype']);
            $money = array('money' => $reinfo['money'], 'hasmoney' => $total);
            money_change($type, $reinfo['userid'], get_com(), $money);

            $this->success('操作成功！', url('reRecord?status=1'));
        } else {
            $this->error('操作失败！');
        }

//            $title='充值成功';
//            $content = '公司已经向'.$reinfo['mobile'].'手机号充值'.$reinfo['money'].'话费请注意查收！'.date('Y-m-d H:i:s');
//            $res = CommonApi::sendMessage($user['uid'],$title,$content);
//            $this->success('话费充值成功',U('mobileRecord'));

    }

    private function reAction($status)
    {
        $id = input('id');
        $reinfo = Db('recharge')->where(array('id' => $id))->find();
        if ($reinfo['status'] != 0) {
            $this->error('该申请已审批');
        }

        $user = Db('member')->where(array('uid' => $reinfo['userid']))->find();
        if (empty($user)) {
            $this->error('该申请人已不存在');
        }

        $data['status'] = $status;
        $res = Db('recharge')->where(array('id' => $id))->update($data);
        return $res;
    }

    /**
     * 充值申请-拒绝
     */
    public function rRefuse()
    {
        $status = -1;
        $res = $this->reAction($status);
        if ($res) {
            $this->success('操作成功', url('wdRecord?status=1'));
        } else {
            $this->success('操作失败');
        }

    }

    /**
     * 充值详情
     */
    public function reDetail()
    {
        $id = input('id');
        $reinfo = Db('recharge')->find($id);
        $this->assign('reinfo', $reinfo);
        $this->assign('title', "充值详情");
        return $this->fetch('redetail');
    }

    /**
     * 充值
     */
    public function reRecord()
    {
        $where = $this->getMap('createtime');
        $map = $where['map'];
        $maps = $where['maps'];
        $usernumber = input('usernumber');
        $status = input('status', -2);

        if (!empty($usernumber)) {
            $maps['usernumber'] = $numwhere['usernumber'] = $usernumber;
            $user = Db('member')->where($numwhere)->find();
            if (!$user) {
                $this->error('用户不存在！');
            } else {
                $map['userid'] = $user['uid'];
            }
        }
        if ($status > -2) {
            $maps['status'] = $map['status'] = $status;
        }

        $list = Db('Recharge')->where($map)->order('createtime desc')->paginate(20, false, ['query' => $maps]);
        $page = $list->render();
        $list = $list->toArray();
        $this->assign('_list', $list['data']);
        $this->assign('page', $page);
        /*追加查询条件*/
        $arr = [
            [
                'type' => 'input',
                'name' => 'usernumber',
                'inputid' => '',
                'readonly' => '',
                'title' => '会员账号',
                'value' => $usernumber,
            ],
            [
                'type' => 'select',
                'name' => 'status',
                'inputid' => '',
                'readonly' => '',
                'title' => '状态',
                'option' => [
                    -2 => '全部',
                    -1 => '拒批',
                    0 => '尚未审核',
                    1 => '同意'
                ],
                'value' => $status,
            ]
        ];
        $this->searchCondition($maps, $arr);

        /*提现统计*/
        $total = Db('recharge')->sum('money');
        /*未审核*/
        $total1 = Db('recharge')->where('status', 0)->sum('money');
        /*拒批*/
        $total2 = Db('recharge')->where('status', -1)->sum('money');
        /*同意*/
        $total3 = Db('recharge')->where('status', 1)->sum('money');

        $this->assign('total', $total);
        $this->assign('total1', $total1);
        $this->assign('total2', $total2);
        $this->assign('total3', $total3);

        $this->assign('title', "充值");
        return $this->fetch('rerecord');
    }

    /**
     * 公司财务
     */
    public function corporateFinance()
    {
        $where = $this->getMap('createtime');
        $map = $where['map'];
        $maps = $where['maps'];

        $end = strtotime($maps['endtime']);
        $start = strtotime($maps['begintime']);
        //统计
        $sql = "select sum(income) as income,sum(expend) as expend,sum(bonus1) as bonus1,sum(bonus2) as bonus2,sum(bonus3) as bonus3,sum(bonus4) as bonus4 from zx_finance where createtime<={$end} and createtime>={$start}";
        $alist = Db('finance')->query($sql);
        $alist[0]['id'] = 0;
        $alist[0]['createtime'] = '总计';
        $first = $this->financeFilter($alist);
        $this->assign('total', $first[0]);

        $list = Db('finance')->where($map)->order('createtime desc')->paginate(20, false, ['query' => $maps]);
        $page = $list->render();
        $list = $list->toArray();

        $list = $this->financeFilter($list['data']);
        $this->assign('_list', $list);
        $this->assign('page', $page);

        $this->searchCondition($maps);
        $this->assign('title', '公司财务');
        return $this->fetch('corporatefinance');
    }

    private function financeFilter($list)
    {
        foreach ($list as &$v) {
            $v['surplus'] = sprintf("%0.2f", $v['income'] - $v['expend']);
            if (is_numeric($v['createtime'])) {
                $v['createtime'] = date('Y-m-d', $v['createtime']);
            }
            if ($v['income'] == 0) {
                $v['outrate'] = 100.00;
            } else {
                $v['outrate'] = round($v['expend'] / $v['income'], 4) * 100;
            }

        }
        return $list;
    }

    /**
     * 财务流水
     */
    public function bonusChange()
    {
        $where = $this->getMap('createtime');
        $map = $where['map'];
        $maps = $where['maps'];
        $usernumber = input('usernumber');
        $changetype = input('changetype', 0);

        if (!empty($usernumber)) {
            $maps['usernumber'] = $usernumber;
            $map['targetuserid'] = Db('member')->where('usernumber', $usernumber)->value('uid');
        }
        if ($changetype > 0) {
            $maps['changetype'] = $map['changetype'] = $changetype;
        }

        $list = Db('money_change')->where($map)->order('createtime desc,id desc')->paginate(20, false, ['query' => $maps]);
        $page = $list->render();
        $list = $list->toArray();
        $this->assign('_list', $list['data']);
        $this->assign('page', $page);

        $changetypes = config('changetype');
        $changetypes[0] = '全部';
        $arr = [
            [
                'type' => 'select',
                'name' => 'changetype',
                'option' => $changetypes,
                'value' => $changetype,
            ],
            [
                'type' => 'input',
                'name' => 'usernumber',
                'inputid' => '',
                'readonly' => '',
                'title' => '会员账号',
                'value' => $usernumber,
            ]
        ];

        $this->searchCondition($maps, $arr);

        $this->assign('search', url('bonusChanged'));
        $this->assign('title', '财务流水');
        return $this->fetch('bonuschange');
    }

    public function bonusChanged()
    {
        $where = $this->getMap('createtime');
        $map = $where['map'];

        $list = Db('money_change')->where($map)->order('createtime desc')->select();
        $title = "财务流水";
        $a = array(
            array('date', '汇总时间'),
            array('usernumber', '会员编号'),
            array('realname', '会员姓名'),
            array('type1', '类型'),
            array('type2', '币种'),
            array('money', '额度')
        );
        foreach ($list as $k => &$v) {
            $v['date'] = date("Y-m-d H:i:s", $v['createtime']);
            $v['usernumber'] = getInfo('usernumber', $v['targetuserid']);
            $v['realname'] = getInfo('realname', $v['targetuserid']);
            $v['type1'] = getChangeType($v['changetype']);
            $v['type2'] = strip_tags(getMoneyType($v['moneytype']));
            $v['money'] = $v['money'];
        }

        exportExcel($title, $a, $list);
    }

    /**
     * 数据统计
     * @return mixed
     */
    public function report()
    {
        $where = $this->getMap('create_time');
        $map = $where['map'];
        $maps = $where['maps'];

        // 现有资产统计
//        $total1 = MemberFinance::sum('hasbill');
        $total2 = MemberFinance::sum('hascp');
//        $total3 = MemberFinance::sum('hasmoney');
//        $total4 = MemberFinance::sum('hasgreen');

        $sql = "select sum(income) as income,sum(expend) as expend,sum(bonus1) as bonus1,sum(bonus2) as bonus2,sum(bonus3) as bonus3,sum(bonus4) as bonus4 from zx_finance ";
        $alist = Db('finance')->query($sql);
        $list = $this->financeFilter($alist);

        $this->assign('list', $list[0]);

        $tax_rate = get_bonus_rule('tax_rate');
        if ($tax_rate > 100 || $tax_rate <= 0) {
            $tax = 0;
        } else {
            $tax = $tax_rate * 0.01;
        }

        $tax_money = $list[0]['income'] * $tax;
        $wd_fee = Withdrawal::where('status', 1)->sum('fee');
        $rechate_total = Db('money_change')->where('changetype', 21)->sum('money');
        $lists = Db('shoplist')->where('status', '>=', 1)->select();
        $costTotal = 0;
        if ($lists) {
            foreach ($lists as $val) {
                $cost = Db('shop')->where('id', $val['goodid'])->value('original_price');
                $costTotal += round($cost * $val['num'], 2);
            }
        }

        $totalNum = Member::where('status', 1)->count();
        $totalNum0 = Member::where('status', 1)->where('userrank', 0)->count();
        $totalNum1 = Member::where('status', 1)->where('userrank', 1)->count();
        $totalNum2 = Member::where('status', 1)->where('userrank', 2)->count();
//        $totalNum3 = Member::where('status', 1)->where('level', 2)->count();

        $sql = "select sum(num) as nums,goodid,goodname from zx_shoplist where status >= 1 group by goodid";
        $goodsInfo = Db::query($sql);
        if ($goodsInfo) {
            foreach ($goodsInfo as &$val) {
                $cateId = Db('shop')->where('id', $val['goodid'])->value('category_id');
                $val['cate_name'] = Db('shop_category')->where('id', $cateId)->value('title');
            }
        }

        $this->assign('goodslist', $goodsInfo);

        $this->assign('total_num', $totalNum);
        $this->assign('total_num0', $totalNum0);
        $this->assign('total_num1', $totalNum1);
        $this->assign('total_num2', $totalNum2);

        $this->assign('tax_money', $tax_money);
        $this->assign('wd_fee', $wd_fee);
        $this->assign('rechate_total', $rechate_total);
        $this->assign('cost_total', $costTotal);

        $this->assign('title', '数据统计');
        return $this->fetch();
    }

    /**
     * 转币记录
     */
    public function tfRecord()
    {
        $where = $this->getMap('createtime');
        $map = $where['map'];
        $maps = $where['maps'];
        $usernumber = input('usernumber');

        if (!empty($usernumber)) {
            $maps['usernumber'] = $usernumber;
            $map['targetuserid'] = Db('member')->where('usernumber', $usernumber)->value('uid');
        }
        $map['changetype'] = 24;

        $list = Db('money_change')->where($map)->order('createtime desc')->paginate(20, false, ['query' => $maps]);
        $page = $list->render();
        $this->assign('_list', $list);
        $this->assign('page', $page);

        $arr = [
            [
                'type' => 'input',
                'name' => 'usernumber',
                'inputid' => '',
                'readonly' => '',
                'title' => '会员账号',
                'value' => $usernumber,
            ]
        ];
        $this->searchCondition($maps, $arr);

        $this->assign('title', '转币记录');
        return $this->fetch();
    }

    /**
     * 抽奖列表
     */
    public function rewardList()
    {
        $reward_names = config('REWARDNAMES');
        $list = Db('reward')->order('create_time desc')->paginate(20);
        $page = $list->render();
        $this->assign('rewards', $reward_names);
        $this->assign('page', $page);
        $this->assign('_list', $list);
        $this->assign('title', '抽奖列表');
        return $this->fetch();
    }

    /**
     * 发放日分红
     */
    public function dayDivid()
    {
        $id = input('id');
        $dayInfo = Db('divid_count')->where(array('id' => $id))->find();
        if ($dayInfo['status'] != 0) {
            $this->error('该分红已发放');
        }
        $sql = "call day_divid()";
        Db::execute($sql);

        $this->success('分红发放成功');
    }

    /**
     * 日分红列表
     */
    public function daylist()
    {
        $_lsit = Db('divid_count')->order('count_date desc')->paginate(20);
        $page = $_lsit->render();
        $this->assign('page', $page);
        $this->assign('_list', $_lsit);
        $this->assign('title', '分红列表');
        return $this->fetch();
    }

    /**
     * 更新日分红
     * @return mixed
     */
    public function edit(request $request)
    {
        if ($request->isGet()) {
            if (!self::$adminInfo['email']) {
                $this->error('缺少邮箱，不可编辑');
            }

            $id = input('id');
            $dayInfo = Db('divid_count')->where('id', $id)->find();
            $this->assign('dayInfo', $dayInfo);
            $this->assign('email', self::$adminInfo['email']);
            return $this->fetch('editday');
        } else {

            $code = input('code');
            if (!$code) {
                $this->error('邮箱验证码缺失');
            }
            if ($code != session('email_code')) {
                $this->error('邮箱验证码错误');
            }

            $data = [
                'money1' => input('money1'),
                'money2' => input('money2')
            ];

            $id = input('id');
            $res = Db('divid_count')->where('id', $id)->update($data);
            if ($res) {
                $this->success('更新成功');
            } else {
                $this->success('更新失败');
            }
        }
    }

    /**
     * 添加分红数据
     */
    public function setDayData()
    {
        $today = strtotime('today');
        $dividCount = Db('divid_count')->where('count_date', $today)->find();
        if ($dividCount) {
            $this->error('今日分红数据已存在！');
        }

        $data = [
            'money1' => 0,
            'money2' => 0,
            'status' => 0,
            'count_date' => $today
        ];

        $res = Db('divid_count')->insert($data);
        if ($res) {
            $this->success('添加成功');
        } else {
            $this->success('添加失败');
        }
    }

    /**
     * 日分红详情
     * @return mixed
     */
    public function dayDetail()
    {
        $id = input('id');
        $dayInfo = Db('divid_count')->where('id', $id)->find();
        $today = strtotime('today');

        $members1 = Db('member')->field('usernumber,realname')->where('status', 1)->where('level', 2)->where('active_time', '<', $today)->where('is_divid1', 1)->select();
        $members2 = Db('member')->field('usernumber,realname')->where('status', 1)->where('level', '>=', 3)->where('active_time', '<', $today)->where('is_divid1', 1)->select();

        $num1 = count($members1);
        $num2 = count($members2);

        $piece1 = round($dayInfo['money1'] / $num1, 2);
        $piece2 = round($dayInfo['money2'] / $num2, 2);

        $this->assign('members1', $members1);
        $this->assign('members2', $members2);
        $this->assign('num1', $num1);
        $this->assign('num2', $num2);
        $this->assign('piece1', $piece1);
        $this->assign('piece2', $piece2);
        $this->assign('dayInfo', $dayInfo);

        $this->assign('title', '日分红详情');
        return $this->fetch('daydetail');
    }

    /**
     * 资金报表
     * @return mixed
     */
    public function financeProfit()
    {
        $starttime = input('begintime');
        $endtime = input('endtime');

        if (($starttime == '') || ($endtime == '')) {
            $time = strtotime('-12 month');
            $datetime = date('Y-m-d', $time);
            $starttime = strtotime($datetime);
            $endtime = time();
        } else {
            $starttime = strtotime("$starttime 00:00:00");
            $endtime = strtotime("$endtime 23:59:59");
        }

        $maps['begintime'] = date('Y-m-d', $starttime);
        $maps['endtime'] = date('Y-m-d', $endtime);

        $days = ceil(($endtime - $starttime) / 86400);
        $totalProfit = $totalWd = 0;
        $arr = [];
        for ($i = 1; $i <= $days; $i++) {
            $starttime1 = $starttime + ($i - 1) * 86400;
            $endtime1 = $starttime1 + 86400;
            $map = [];
            $map['create_time'] = array(array('gt', $starttime1), array('lt', $endtime1));
            $map['status'] = ['egt', 1];
            $lists = Db('shoplist')->where($map)->order('create_time asc')->select();

            $profit1 = $profit2 = $profit3 = $profit4 = $profit5 = $profit6 = $profit7 = $profit8 = 0;
            foreach ($lists as $k => $v) {
                $order = Db('shop_order')->where('orderid', $v['tag'])->find();

                switch ($order['mark']) {
                    case 'vip':
                        if ($order['tuijianid'] <= 0) {
                            $profit1 += $v['total1'];/*公司vip产品收入*/
                        } else {
                            $userrank = Db('member')->where('uid', $order['tuijianid'])->value('userrank');
                            switch ($userrank) {
                                case 5:
                                    $profit2 += $v['total1'];/*钻石合伙人vip产品收入*/
                                    break;
                                case 4:
                                    $profit3 += $v['total1'];/*金牌合伙人vip产品收入*/
                                    break;
                                case 3:
                                    $profit4 += $v['total1'];/*银牌合伙人vip产品收入*/
                                    break;
                            }
                        }
                        break;
                    case 'shop':
                        $profit5 += $v['total1'];/*商城产品收入*/
                        break;
                    case 'cash':
                        $profit6 += $v['total1'];/*积分加现金产品收入*/
                        break;
                    case 'free':
                        $profit7 += $order['transfee'];/*免费试用产品收入*/
                        break;
                    case 'vipt':
                        $profit8 += $order['transfee'];/*拓客产品收入*/
                        break;
                }
            }

            unset($map['create_time']);
            $map['createtime'] = array(array('gt', $starttime1), array('lt', $endtime1));
            $wdMoney = Db('withdrawal')->where($map)->sum('money');
            $wdFee = Db('withdrawal')->where($map)->sum('fee');
            $wd = $wdMoney + $wdFee;

            $profit = $profit1 + $profit2 + $profit3 + $profit4 + $profit5 + $profit6 + $profit7 + $profit8;
            if ($profit > 0) {
                $k = date('Y-m-d', $starttime1);
                $arr[$k] = [
                    'date' => $k,
                    'profit' => $profit,
                    'profit1' => $profit1,
                    'profit2' => $profit2,
                    'profit3' => $profit3,
                    'profit4' => $profit4,
                    'profit5' => $profit5,
                    'profit6' => $profit6,
                    'profit7' => $profit7,
                    'profit8' => $profit8,
                    'wd' => $wd
                ];
            }

            $totalProfit += $profit;
            $totalWd += $wd;
        }

        $this->searchCondition($maps);
        $this->assign('_list', $arr);
        $this->assign('totalProfit', $totalProfit);
        $this->assign('totalWd', $totalWd);
        $this->assign('title', '资金报表');
        return $this->fetch('financeprofit');
    }
}
